package org.unidata.mdm.meta.service;

import org.unidata.mdm.core.type.model.AttributeElement;
import org.unidata.mdm.core.type.model.EntityElement;
import org.unidata.mdm.meta.service.impl.data.instance.AttributeImpl;
import org.unidata.mdm.meta.type.model.ArrayValueType;
import org.unidata.mdm.meta.type.model.attributes.ArrayMetaModelAttribute;
import org.unidata.mdm.meta.type.model.attributes.CodeMetaModelAttribute;
import org.unidata.mdm.meta.type.model.attributes.SimpleMetaModelAttribute;
import org.unidata.mdm.meta.type.model.entities.LookupEntity;

/**
 * @author Mikhail Mikhailov on Oct 19, 2020
 * Fix lookup link attribute type
 */
public interface LookupReferenceSupport {
    /**
     * Fixes the type of the link attribute 'el' to point properly to the code attribute from 'l'.
     * @param l the lookup element
     * @param el the attribute to fix
     */
    default void fixLookupLinkType(EntityElement l, AttributeElement el) {

        // el is our attribute
        // l is the target
        CodeMetaModelAttribute codeAttr
            = (CodeMetaModelAttribute) ((AttributeImpl) l.getLookup().getCodeAttribute())
                .getAttribute();

        setLookupLinkType(codeAttr, el);
    }

    default void fixLookupLinkType(LookupEntity l, AttributeElement el) {
        // el is our attribute
        // l is the target
        setLookupLinkType(l.getCodeAttribute(), el);
    }

    private void setLookupLinkType(CodeMetaModelAttribute codeAttr, AttributeElement el) {

        AttributeImpl aii = (AttributeImpl) el;
        if (aii.isArray()) {
            ArrayMetaModelAttribute source = (ArrayMetaModelAttribute) aii.getAttribute();
            source.setLookupEntityCodeAttributeType(ArrayValueType.fromValue(codeAttr.getSimpleDataType()));
        } else if (el.isSimple()) {
            SimpleMetaModelAttribute source = (SimpleMetaModelAttribute) aii.getAttribute();
            source.setLookupEntityCodeAttributeType(codeAttr.getSimpleDataType());
        }
    }
}
